package com.wika.basics.widget

import android.content.Context
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.StateListDrawable
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatButton
import androidx.core.content.ContextCompat
import com.wika.basics.R

/**
 *@Description: 圆角按钮
 *@Date: 2024/3/7 8:49
 *@Author: WangWeiShuo
 */
class RoundButton @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
): AppCompatButton(context,  attrs, defStyleAttr) {

    init {
        initAttrs(context,attrs)
        setOnClickListener {
        }
    }

    private fun initAttrs(context: Context, attrs: AttributeSet?) {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.RoundButton)
        val bgColor = typedArray.getColor(R.styleable.RoundButton_normalColor, ContextCompat.getColor(context, R.color.gray_27000000))
        val pressedColor = typedArray.getColor(R.styleable.RoundButton_pressedColor, ContextCompat.getColor(context, R.color.gray_817B7B))
        val buttonCorner = typedArray.getDimensionPixelSize(R.styleable.RoundButton_cornerRadius, 0)

        //生成圆角图片
        val normalDrawable = GradientDrawable()
        normalDrawable.setColor(bgColor)
        normalDrawable.cornerRadius = buttonCorner.toFloat()

        //生成一张半透明的颜色 可自定义
        val pressedDrawable = GradientDrawable()
        pressedDrawable.setColor(pressedColor)
        pressedDrawable.cornerRadius = buttonCorner.toFloat()

//        //生成一个图层叠加的图片 上面用灰色盖住 模拟变暗效果
//        val arr = arrayOf(normalDrawable, bgcDrawable1)
//        val layerDrawable = LayerDrawable(arr)

        //设置点击后的效果
        val stateListDrawable = StateListDrawable()
        stateListDrawable.addState(intArrayOf(android.R.attr.state_pressed), pressedDrawable)
        stateListDrawable.addState(intArrayOf(), normalDrawable)

        background = stateListDrawable
        typedArray.recycle()
    }

}